<template>
  <div class="consultation">
    <h2>火车管理</h2>
    <div class="consultation-block">
      <div class="flex-center">
        <el-input style="width: 150px;" size="mini" v-model="name" placeholder="请输入车次"></el-input>
        <el-button type="success" size="mini" @click="refreshTable">查询</el-button>
        <el-button type="primary" size="mini" @click="openDialog('add')">添加火车信息</el-button>
      </div>
      <div class="table" v-loading="tableLoading">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="name" label="车次"> </el-table-column>
          <el-table-column prop="type" label="类型"> </el-table-column>
          <el-table-column prop="startStation" label="起始站点"> </el-table-column>
          <el-table-column prop="startTime" label="发车时间"> </el-table-column>
          <el-table-column prop="line" label="途径" :formatter="formatLine"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="openDialog('edit', scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deleteData(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isVisible"
      width="70%"
      :before-close="handleClose"
    >
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="form"
        label-width="120px"
        class="demo-form"
      >
        <el-form-item label="车次" prop="name" style="margin-bottom: 10px;">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type" style="margin-bottom: 10px;">
          <el-radio-group v-model="form.type">
            <el-radio :label="item" :key="index" v-for="(item, index) in typeList">{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="起始站点" prop="startStation" style="margin-bottom: 10px;">
          <el-select v-model="form.startStation" placeholder="请选择">
            <el-option
              v-for="item in stationList"
              :key="item.stationName"
              :label="item.stationName"
              :value="item.stationName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发车时间" prop="startTime" style="margin-bottom: 10px;">
          <el-time-picker
            v-model="form.startTime">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="途径" prop="line" style="margin-bottom: 10px;">
          <el-button size="mini" type="primary" @click="doAdd">添加</el-button>
          <div class="each-station" v-for="(line, index) in form.line" :key="index">
            <div style="width: 100%;margin-bottom: 10px;" class="flex-center">
              站点：
              <el-select style="width: 120px;" size="mini" v-model="line.station" placeholder="请选择">
                <el-option
                  v-for="item in stationList"
                  :key="item.stationName"
                  :label="item.stationName"
                  :value="item.stationName">
                </el-option>
              </el-select>
              本站时长：
              <el-input-number :step="10" :min="0" size="mini" v-model="line.time"></el-input-number>
            </div>
            <div style="width: 100%;" class="flex-center">
              <div>票价（元）:</div>
              无座：
              <el-input-number :step="10" :min="0" size="mini" v-model="line.price[0]"></el-input-number>
              硬座：
              <el-input-number :step="10" :min="0" size="mini" v-model="line.price[1]"></el-input-number>
              硬卧：
              <el-input-number :step="10" :min="0" size="mini" v-model="line.price[2]"></el-input-number>
              软卧：
              <el-input-number :step="10" :min="0" size="mini" v-model="line.price[3]"></el-input-number>
            </div>
            <el-button class="delete" size="mini" type="danger" icon="el-icon-delete" @click="doDelete(index)"></el-button>
          </div>
        </el-form-item>
        <el-form-item label="座位总数量" prop="seats" style="margin-bottom: 10px;">
          <div>本次列车总车厢八节，每节车厢10排，每排五个座位，请合理安排位置。</div>
          <div v-for="(seat, index) in form.seats" :key="index">
            {{seat.name}}：
            <el-input-number size="mini" v-model="seat.cnt"></el-input-number>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="!form.examine">
        <el-button type="primary" @click="submitForm()">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment';
import { getTrain, deleteTrain, updateTrain, addTrain, getStation } from "../service.js";
export default {
  name: "home",
  mounted() {
    getStation({
      page: 1,
      pageSize: 1000
    }).then(res => {
      this.stationList = res.data.data;
    })
    this.refreshTable();
  },
  data() {
    return {
      tableData: [],
      stationList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      name: '',
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      form: {},
      typeList: ['火车', '动车', '高铁'],
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        startStation: [{ required: true, message: '请输入', trigger: 'blur' }],
        startTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        line: [{ required: true, message: '请选择', trigger: 'blur' }],
      }
    };
  },
  methods: {
    openDialog(type, row = {}) {
      if (type === 'add') {
        this.dialogTitle = "添加";
        this.form = {
          name: "",
          type: "高铁",
          line: [],
          seats: [
            {
              name: '无座',
              cnt: 100
            },
            {
              name: '硬座',
              cnt: 100
            },
            {
              name: '硬卧',
              cnt: 100
            },
            {
              name: '软卧',
              cnt: 100
            }
          ],
          startStation: '',
          startTime: ''
        };
      } else {
        this.dialogTitle = "编辑";
        this.form = JSON.parse(JSON.stringify({
          ...row,
          startTime: new Date(`2023-03-27 ${row.startTime}`),
          seats: JSON.parse(row.seats),
          line: JSON.parse(row.line),
        }))
        console.log(this.form)
      }
      this.isVisible = true;
    },
    handleClose() {
      this.isVisible = false;
    },
    handleCurrentChange(index) {
      this.currentPage = index
      this.refreshTable()
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 车次名称限制
          if (this.form.name.length > 6) {
            this.$message.error('车次不能超过六个字符');
            return
          }
          if (this.form.type === '火车' && !this.form.name.startsWith('K')) {
            this.$message.error('火车车次请以K开头');
            return
          }
          if (this.form.type === '动车' && !this.form.name.startsWith('D')) {
            this.$message.error('动车车次请以D开头');
            return
          }
          if (this.form.type === '高铁' && !this.form.name.startsWith('G')) {
            this.$message.error('高铁车次请以G开头');
            return
          }
          let total = this.form.seats.slice(1).reduce((a, b) => {
            return a + b.cnt
          }, 0)
          console.log(total)
          if (total > 400) {
            this.$message.error('座位数超出限制，请合理分配')
            return
          }
          // 是否有相同的站
          let totalLine = this.form.line.length;
          let lineName = this.form.line.map(v => v.station).concat(this.form.startStation)
          console.log(totalLine, lineName)
          if (Array.from(new Set(lineName)).length <= totalLine) {
            this.$message.error('途径站点重复')
            return
          }
          if (this.dialogTitle === "添加") {
            console.log(this.form)
            addTrain({
              ...this.form,
              line: JSON.stringify(this.form.line),
              startTime: moment(this.form.startTime).format('HH:mm:ss'),
              seats: JSON.stringify(this.form.seats)
            }).then(res => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.refreshTable();
                this.isVisible = false;
              } else {
                this.$message.error("车次不能重复");
              }
            })
            return
          }
          console.log(this.form.startTime)
          updateTrain(this.form.id, {
            ...this.form,
            line: JSON.stringify(this.form.line),
            startTime: moment(this.form.startTime).format('HH:mm:ss'),
            seats: JSON.stringify(this.form.seats)
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success("操作成功");
              this.refreshTable();
              this.isVisible = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    addData() {
      this.dialogTitle = "新增";
      this.isVisible = true;
    },
    refreshTable() {
      getTrain({
        page: this.currentPage,
        pageSize: this.pageSize,
        name: this.name
      }).then((res) => {
        this.tableData = res.code === 200 ? res.data.data : [];
        this.total = res.data.total
      });
    },
    deleteData(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteTrain(row.id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.refreshTable();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    formatLine(row) {
      let line = JSON.parse(row.line)
      console.log(line)
      return line.map(v => v.station).join('-')
    },
    doAdd() {
      if (!this.form.line) {
        this.form.line = []
      }
      this.form.line.push({
        station: '',
        time: 10,
        price: [10, 20, 40, 60]
      })
    },
    doDelete(index) {
      this.form.line.splice(index, 1)
    }
  },
};
</script>

<style scoped lang="scss">
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.img-blocks {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
.flex-center {
  display: flex;
  gap: 10px;
  align-items: center;
}

.each-station {
  position: relative;
  border-bottom: 1px solid #666;

  .delete {
    position: absolute;
    right: 20px;
    top: 10px;
  }
}
</style>
